/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package nameservice;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Logger;
import javax.swing.SwingWorker;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Mariusz, Pascal
 */
public class NameServiceCore extends SwingWorker<Object, Object> {

    private ConcurrentHashMap<String, ServantEntrie> refMap =
            new ConcurrentHashMap<String, ServantEntrie>();
    private ServerSocket serverSocket;
    private int port;
    private ExecutorService threadPool =
            Executors.newFixedThreadPool(3);
    private Logger logger;
    private DefaultTableModel model;

    public NameServiceCore(int port, DefaultTableModel model) {
        this.port = port;
        this.model = model;
        this.logger = NameServiceGUI.getLogger();
    }

    @Override
    protected Object doInBackground() throws Exception {
        try {
            serverSocket = new ServerSocket(port);
            logger.info("Lausche auf Port " + port);
            while (true) {
                Socket connectionSocket = serverSocket.accept();
                logger.info("Verbindung aufgenommen zu " +
                        connectionSocket.getInetAddress().getCanonicalHostName());
                threadPool.execute(new RequestHandler(this, connectionSocket));
            }
        } catch (IOException e) {
            logger.severe("IOException " + e);
        }
        return null;
    }

    public ServantEntrie lookup(String name) { // getservant
        logger.info("Lookup von " + name);
        return refMap.get(name);
    }

    public void rebind(ServantEntrie servant, String name) { // addservant
        logger.info("Rebind von " + name + " servant: " + servant);
        refMap.put(name, servant);
        model.addRow(new Object[]{servant.getHost(), servant.getPort(), servant.getName(), servant.getClassname()});
    }
}
